package rcp.iphex2.ui.projectexplorer.commandhandler;

import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import rcp.iphex2.SharedIds;
import rcp.iphex2.dialogs.AddMetainformationDialog;
import rcp.iphex2.model.Project;
import rcp.iphex2.model.ProjectEntry;
import rcp.iphex2.ui.projectexplorer.ProjectExplorerView;


public class AddMetaInformationHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		AddMetainformationDialog dialog = new AddMetainformationDialog(window.getShell());
		dialog.open();
		String metainformationName = dialog.getName();
		String metainformationValue = dialog.getValueForSelection();

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
		List<Object> structuredSelectionList = selection.toList();
		Project rootProject = null;
		for (Object object : structuredSelectionList) {
			if (object instanceof ProjectEntry) {
				ProjectEntry projectEntry = (ProjectEntry) object;
				rootProject = projectEntry.getRootProject();
				projectEntry.addMetainformation(metainformationName, metainformationValue);

			}
		}

		if (rootProject != null) {
			String PROJECT_EXPLORER_VIEW_ID = SharedIds.PROJECT_EXPLORER_VIEW_ID;
			IViewPart projectExplorer = HandlerUtil.getActivePart(event).getSite().getPage().findView(PROJECT_EXPLORER_VIEW_ID);
			final ProjectExplorerView projectExplorerView = (ProjectExplorerView) projectExplorer;
			projectExplorerView.update(true);
		}
		return null;
	}
}
